package org.example.algorithm.heap;

import java.util.PriorityQueue;

public class MedianFinderSolution {
    private PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b)->b-a);
    private PriorityQueue<Integer> minHeap = new PriorityQueue<>();

    public MedianFinderSolution() {

    }

    public void addNum(int num) {
        if (maxHeap.size() == minHeap.size()) {
            minHeap.offer(num);
            maxHeap.offer(minHeap.poll());
        } else {
            maxHeap.offer(num);
            minHeap.offer(maxHeap.poll());
        }
    }

    public double findMedian() {
        if (maxHeap.size() == minHeap.size()) {
            return (maxHeap.peek() + minHeap.peek()) / 2.0;
        }
        return maxHeap.peek();
    }
}
